#ifndef TCPSERVERFORM_H
#define TCPSERVERFORM_H

#include <QWidget>
#include <mutex>
#include <unordered_map>

#include "TcpServer.h"
#include "sessionitem.h"

namespace Ui {
class TcpServerForm;
}

class TcpServerForm : public QWidget
{
    Q_OBJECT

public:
    explicit TcpServerForm(QWidget *parent = 0);
    ~TcpServerForm();

    void AcceptSession(std::shared_ptr<TcpSession> &session);

private slots:
    void on_ListenButton_clicked();
    void on_TcpSndButton_clicked();
    void on_ClearRecordBtn_clicked();
    void on_SaveRecordBtn_clicked();

private slots:
    void SlotRead(const QString&, const QByteArray&);
    void SlotDisconnect(const QString&);

private:
    Ui::TcpServerForm *ui;

    void InitForm();
    SessionItem* NewSessionItem(std::shared_ptr<TcpSession> &);

    void WriteLog(QString&);
    void WriteLog(const char*);
    void WriteLogNoTime(QString &);
    void WriteLogNoTime(const char*);

    void ParseDeviceFrame(const QByteArray &data);
    const char* GetSensorStatusStr(quint8);

    void SndToAllSession(QByteArray&);
    void SndToSession(QString&, QByteArray&);

    //字节数组转16进制字符串
    QString byteArrayToHexStr(const QByteArray &data);
    //字节数组转Ascii字符串
    QString byteArrayToAsciiStr(const QByteArray &data);
    //10进制转16进制字符串,补零.
    QString decimalToStrHex(int decimal);

    QByteArray hexStrToByteArray(const QString&);
    int hexStrToChar(char ch);

    void MapClear();
    void DisconnectClear(const QString&);

private:
    TcpServer* m_Server;
    bool bIsListen = false;
    quint16 m_Port;

    QByteArray m_FrameBuff;

    std::mutex m_Lock;
    std::unordered_map<std::string, SessionItem*> m_SessionMap;
};

#endif // TCPSERVERFORM_H
